//
//  GridView.m
//  DragViewDemo
//
//  Created by 吳瀾洲 on 2020/8/18.
//  Copyright © 2020 kingboyrang. All rights reserved.
//

#import "GridView.h"
#import "ButtonItem.h"


@interface GridView ()

// 开始拖动的view的下一个view的CGPoint（如果开始位置是0 结束位置是4 nextPoint值逐个往下算）
@property (nonatomic,assign) CGPoint nextPoint;
// 用于赋值CGPoint
@property (nonatomic,assign) CGPoint valuePoint;

@property (nonatomic,strong) UIImageView *backgroundImageView;

@end

@implementation GridView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

//背景色
- (UIImageView *)backgroundImageView{
    if (_backgroundImageView == nil) {
        _backgroundImageView = [[UIImageView alloc] initWithFrame:self.bounds];
    }
    return _backgroundImageView;
}

//创建按钮
- (void)createGrid{
    
    if (self.pageModel == nil) {
        return;
    }
    if (self.pageModel.background && [self.pageModel.background length]>0) {
        //设置背景
    }
        
    //创建按钮
    BOOL portrait = YES;
    UIDeviceOrientation deviceOrientation=[UIDevice currentDevice].orientation;
    if (deviceOrientation == UIDeviceOrientationLandscapeLeft || deviceOrientation == UIDeviceOrientationLandscapeRight) {
        //横屏
        portrait = NO;
    }
    NSArray <NSArray <ButtonModel *> *> *list=[self.pageModel showInView:self buttons:self.pageModel.buttonList isPortrait:portrait];
    if (list && [list count]>0) {
        
        for (NSInteger i=0;i< [list count];i++) {
            
            NSArray <ButtonModel *> *itemArr = [list objectAtIndex:i];
            for (NSInteger j=0; j< [itemArr count]; j++) {
                ButtonModel *model = [itemArr objectAtIndex:j];
               
                ButtonItem *btnItem = [[ButtonItem alloc] initWithModel:model frame:model.frame];
                btnItem.tag = model.tag;
                // 长按手势
                UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
                [btnItem addGestureRecognizer:longPress];
                [self addSubview:btnItem];
                
            }
        }
    
    }
}


/**
 *  长按手势
 */
-(void)longPress:(UIGestureRecognizer*)recognizer{
    
    if (![recognizer.view isKindOfClass:[ButtonItem class]]) {
        return;
    }
    //
    UIButton *recognizerView = (UIButton *)recognizer.view;
    
    // 禁用其他按钮的拖拽手势
    for (UIButton * bt in self.subviews) {
        if (bt!=recognizerView) {
            bt.userInteractionEnabled = NO;
        }
    }
    
     __weak __typeof(self)weakSelf = self;
    // 长按视图在父视图中的位置（触摸点的位置）
    CGPoint recognizerPoint = [recognizer locationInView:self];
    NSLog(@"_____%@",NSStringFromCGPoint(recognizerPoint));
    
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        
        // 开始的时候改变拖动view的外观（放大，改变颜色等）
        [UIView animateWithDuration:0.2 animations:^{
            recognizerView.transform = CGAffineTransformMakeScale(1.3, 1.3);
            recognizerView.alpha = 0.7;
        }];
        
        // 把拖动view放到最上层
        [self bringSubviewToFront:recognizerView];
        
        // valuePoint保存最新的移动位置
        self.valuePoint = recognizerView.center;
        
    }else if(recognizer.state == UIGestureRecognizerStateChanged){
        
        // 更新pan.view的center
        recognizerView.center = recognizerPoint;
        
        /**
         * 可以创建一个继承UIButton的类(MyButton)，这样便于扩展，增加一些属性来绑定数据
         * 如果在self.view上加其他控件拖拽会奔溃，可以在下面方法里面加判断MyButton，也可以把所有按钮放到一个全局变量的UIView上来替换self.view
         
         */
        for (UIButton * bt in self.subviews) {
           
            // 判断是否移动到另一个view区域
            // CGRectContainsPoint(rect,point) 判断某个点是否被某个frame包含
            if (CGRectContainsPoint(bt.frame, recognizerView.center)&&bt!=recognizerView)
            {
                NSLog(@"bt_______%@",bt);
                // 开始位置
                NSInteger fromIndex = recognizerView.tag - KButtonItemTag;
                
                // 需要移动到的位置
                NSInteger toIndex = bt.tag - KButtonItemTag;
                NSLog(@"开始位置=%ld  结束位置=%ld",fromIndex,toIndex);
                
                // 往后移动
                if ((toIndex-fromIndex)>0) {
                    
                    // 从开始位置移动到结束位置
                    // 把移动view的下一个view移动到记录的view的位置(valuePoint)，并把下一view的位置记为新的nextPoint，并把view的tag值-1,依次类推
                    [UIView animateWithDuration:0.2 animations:^{
                        
                        __strong __typeof(weakSelf)strongSelf = weakSelf;
                        
                        for (NSInteger i = fromIndex+1; i<=toIndex; i++) {
                            UIButton * nextBt = (UIButton*)[self viewWithTag:KButtonItemTag+i];
                            strongSelf.nextPoint = nextBt.center;
                            nextBt.center = strongSelf.valuePoint;
                            strongSelf.valuePoint = strongSelf.nextPoint;
                            
                            nextBt.tag--;
                            //[nextBt setTitle:[NSString stringWithFormat:@"tag值%ld",nextBt.tag] forState:UIControlStateNormal];
                            
                        }
                        recognizerView.tag = KButtonItemTag + toIndex;
                        //[recognizerView setTitle:[NSString stringWithFormat:@"tag值%ld",recognizerView.tag] forState:UIControlStateNormal];
                        
                    }];
                    
                }
                // 往前移动
                else
                {
                    // 从开始位置移动到结束位置
                    // 把移动view的上一个view移动到记录的view的位置(valuePoint)，并把上一view的位置记为新的nextPoint，并把view的tag值+1,依次类推
                    [UIView animateWithDuration:0.2 animations:^{
                        __strong __typeof(weakSelf)strongSelf = weakSelf;
                        
                        for (NSInteger i = fromIndex-1; i>=toIndex; i--) {
                            UIButton * nextBt = (UIButton*)[self viewWithTag:KButtonItemTag+i];
                            strongSelf.nextPoint = nextBt.center;
                            nextBt.center = strongSelf.valuePoint;
                            strongSelf.valuePoint = strongSelf.nextPoint;
                            
                            nextBt.tag++;
                            //[nextBt setTitle:[NSString stringWithFormat:@"tag值%ld",nextBt.tag] forState:UIControlStateNormal];
                        }
                        recognizerView.tag = KButtonItemTag + toIndex;
                        //[recognizerView setTitle:[NSString stringWithFormat:@"tag值%ld",recognizerView.tag] forState:UIControlStateNormal];
                        
                    }];
                    
                }
                
                
                
            }
            
        }
        
        
    }else if(recognizer.state == UIGestureRecognizerStateEnded){
        // 恢复其他按钮的拖拽手势
        for (UIButton * bt in self.subviews) {
            if (bt!=recognizerView) {
                bt.userInteractionEnabled = YES;
            }
        }

        // 结束时候恢复view的外观（放大，改变颜色等）
        [UIView animateWithDuration:0.2 animations:^{
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            
            recognizerView.transform = CGAffineTransformMakeScale(1.0, 1.0);
            recognizerView.alpha = 1;
            
            recognizerView.center = strongSelf.valuePoint;
        }];
    }
    
    
    
}

//重新布局
- (void)autoLayout{
    
     BOOL portrait = YES;
    UIDeviceOrientation deviceOrientation=[UIDevice currentDevice].orientation;
    if (deviceOrientation == UIDeviceOrientationLandscapeLeft || deviceOrientation == UIDeviceOrientationLandscapeRight) {
        //横屏
        portrait = NO;
    }
    
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
    for (UIView * bt in self.subviews) {
        if ([bt isKindOfClass:[ButtonItem class]]) {
            ButtonItem *btn = (ButtonItem *)bt;
            [arr addObject:btn.buttonModel];
        }
    }
    
    NSArray <NSArray <ButtonModel *> *> *list=[self.pageModel showInView:self buttons:arr isPortrait:portrait];
    //重新设置frame
    if (list && [list count]>0) {
        
        for (NSInteger i=0;i< [list count];i++) {
            
            NSArray <ButtonModel *> *itemArr = [list objectAtIndex:i];
            for (NSInteger j=0; j< [itemArr count]; j++) {
                ButtonModel *model = [itemArr objectAtIndex:j];
               
                ButtonItem *btnItem = (ButtonItem *)[self viewWithTag:model.tag];
                if (btnItem) {
                    btnItem.frame = model.frame;
                }
                
            }
        }
    
    }
    
}

- (void)layoutSubviews{
    [super layoutSubviews];
    [self autoLayout];
    
}


@end
